package com.ssims.common.util;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 * @description Created by coliza on 2015/9/8.
 */
@MappedTypes({char[].class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class CharArrayTypeHandler extends BaseTypeHandler<char[]> {
    @Override
    public char[] getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return getStringArray(rs.getString(columnName));
    }

    @Override
    public char[] getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return this.getStringArray(rs.getString(columnIndex));
    }

    @Override
    public char[] getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return this.getStringArray(cs.getString(columnIndex));
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    char[] parameter, JdbcType jdbcType) throws SQLException {
        //由于BaseTypeHandler中已经把parameter为null的情况做了处理，所以这里我们就不用再判断parameter是否为空了，直接用就可以了
        StringBuffer result = new StringBuffer();
        for (char value : parameter)
            result.append(value).append(",");
        result.deleteCharAt(result.length() - 1);
        ps.setString(i, result.toString());
    }

    private char[] getStringArray(String columnValue) {
        if (columnValue == null)
            return null;
        return columnValue.toCharArray();
    }
}
